<template>
  <section>
    <el-card>
      <el-row :gutter="0">
        <el-col :span="24" class="mb20">
          <el-col :span="24">
            <div
              class="table_content"
              style="margin-bottom: 1px"
            >
              <el-row :gutter="4">
                <el-form
                  :model="searchDto"
                  :inline="true"
                  ref="searchForm"
                  label-position="left"
                  class="demo-form-inline"
                  label-width="100px"
                >
                  <el-form-item
                    label="部门名称"
                    prop="name"
                    class="clear_item-margin-bottom labdep"
                  >
                    <el-input
                      v-model="searchDto.name"
                      placeholder="请输入名字"
                      class="mr10 it350 wanner"
                    />
                  </el-form-item>
                  <el-form-item label="部门类型" prop="type" class="clear_item-margin-bottom labdep right">
                    <el-select v-model="searchDto.type" placeholder="请选择" style="margin-left:-25px ">
                      <el-option label="全部" value=""></el-option>
                      <el-option
                        v-for="item in deptTypeList"
                        :key="item.name"
                        :label="item.name"
                        :value="item.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-row>
            </div>
            <div style="float: left; margin-bottom: 10px;">
              <el-button
                type="primary"
                size="small"
                icon="el-icon-circle-plus"
                @click="showDeptViewTrue()"
              >新增部门
              </el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-circle-plus"
                @click="setApplyDept()">设置依申请部门
              </el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-search"
                @click="getDepartment(1)"
              >查询
              </el-button
              >
              <el-button
                type="primary"
                @click="resetForm('searchForm')"
                size="small"
                icon="el-icon-remove"
              >重置
              </el-button
              >
            </div>
            <el-table
              style="margin-top: 25px;border: 1px solid #ededed;"
              :data="deptListPage.list"
              table
              border
              stripe
              :default-sort="{prop: 'no', order: 'descending'}"
            >
              <el-table-column
                prop="no"
                label="编号"
                sortable
                align="center"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="name"
                label="部门名称"
                align="center"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                prop="phone"
                label="部门电话"
                align="center"
                show-overflow-tooltip
              ></el-table-column>

              <!--tool-->
              <el-table-column
                label="管理"
                width="300"
                align="center"
                fixed="right"
              >
                <template slot-scope="scope">
                  <el-tooltip content="点我编辑" placement="top">
                    <el-button
                      size="mini"
                      icon="el-icon-edit"
                      @click="deptEdit(scope.row)"
                    ></el-button>
                  </el-tooltip>

                  <el-tooltip content="点我删除" placement="top">
                    <el-button
                      size="mini"
                      icon="el-icon-delete"
                      @click="delDept(scope.row.id)"
                    ></el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
              <!--tool-->
            </el-table>
            <el-col :span="24" class="mt20 ml20">
              <el-pagination
                style="float:right"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="deptListPage.currPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="searchDto.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="deptListPage.totalRow"
              >
              </el-pagination>
            </el-col>
          </el-col>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog :visible.sync="showDeptView" title="编辑/新增 部门:" width="40%">
      <el-row>
        <el-col :span="24" class="mt20">
          <el-form
            ref="deptViews"
            :rules="rules"
            :model="deptView"
            label-width="90px"
          >
            <el-form-item label="部门名称:" prop="name">
              <el-input v-model="deptView.name"></el-input>
            </el-form-item>
            <el-form-item label="部门编号:" prop="no">
              <el-input v-model="deptView.no"></el-input>
            </el-form-item>
            <el-form-item label="部门电话:" prop="phone">
              <el-input v-model="deptView.phone"></el-input>
            </el-form-item>
            <el-form-item label="类型:" prop="deptType">
              <el-select v-model="deptView.deptType" filterable placeholder="请选择">
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="参与统计:" prop="isCount">
              <el-switch
                v-model="deptView.isCount"
                active-text="是"
                active-value= '0'
                inactive-value= '1'
                inactive-text="否">
              </el-switch>
            </el-form-item>
            <el-form-item>
              <span style="float: left;">
                <el-button
                  type="primary"
                  size="small"
                  @click="saveDeptView('deptViews')"
                >保存</el-button
                >
              </span>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      :visible.sync="showApplyDept"
      title="依申请部门设置:"
      width="40%"
      destroy-on-close
    >
      <el-row style="text-align: center">
        <el-col :span="24">
          <el-button type="primary" size="mini" @click="saveApplyDept()"
          >保存
          </el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="closeApplyDialog"
          >返回
          </el-button
          >
        </el-col>
        <el-col :span="24" class="mt20">
          <el-table
            :data="deptAll"
            table
            border
            ref="multipleTable"
            @selection-change="handleSelectionChange"
            stripe>
            <el-table-column
              type="selection"
              width="55"
            ></el-table-column>
            <el-table-column
              prop="id"
              label="编号"
              sortable
              align="center"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="name"
              label="部门名称"
              sortable
              align="center"
              show-overflow-tooltip></el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-dialog>
  </section>
</template>

<script>
  import PageLayout from "@/components/page-layout";
  import {mapGetters} from "vuex";

  // import ImageCover from "@/components/image-cover";
  import Status from "@/libs/status";
  // import Moment from "moment";
  // import _ from "lodash";
  import SelectTree from "@/components/select-tree";

  export default {
    name: "department",
    created() {
      this.getDeptList();

      this.getDepartment(1);
      // this.$store.dispatch("deptListNotAllUsingPOSTS").then(ret => {});
      //部门类型字典ID
      let deptTypeDitcId = "4fcf0e4a18a146a39eaa08b5db6eb7b0";
      this.getDeptType(deptTypeDitcId);
    },

    mounted() {
      this.getDeptAll()
    },
    watch: {},
    data() {
      return {
        types: Status.deptTypes,
        showApplyDept: false,
        //上传文件
        fileList: [],
        //导出文件
        derive: {},
        //导出按键开关
        exportTheSwitch: false,

        showDeptView: false,
        props: {
          value: "id",
          label: "name",
          children: "children"
        },
        searchDto: {
          endTime: "",
          pageSize: 10,
          startTime: "",
          name: "",
          type: "",
          no: ""
        },
        deptTypeList: [],
        filterText: "",
        defaultProps: {
          children: "children",
          label: "label"
        },
        setProperty: {
          children: "children",
          label: "label",
          checkStrictly: true,
          value: "id"
        },
        valueId: 0,
        pageSize: 4,
        pageIndex: "",
        clickID: "",
        rules: {
          name: [{required: true, message: "请输入部门名称", trigger: "blur"}],
          parentId: [{required: true, message: "请选择上级", trigger: "blur"}],
          no: [{required: true, message: "请选择部门编号", trigger: "blur"}],
          deptType: [{required: true, message: "请选择部门类型", trigger: "blur"}]
        },
        uploadUrl: window.api.domain + "/excel/import/dept",
        headers: {
          appKey: "dangjian",
          clientId: "ADMIN",
          Authorization: window.sessionStorage.getItem("token")
        },
        selectData: [],
        deptAll: [],
        checkedData: []
      };
    },
    computed: {
      ...mapGetters({
        showSearchPanel: "showSearchPanel",
        deptList: "deptList",
        currentDep: "currentDep",
        userList: "userList",
        deptListPage: "deptListPage",
        deptNotAllList: "deptNotAllList",
        deptView: "deptView",
        deptSeleteList: "deptSeleteList"
      }),
      /* 转树形数据 */
      optionData() {
        let cloneData = JSON.parse(JSON.stringify(this.deptSeleteList)); // console.log(cloneData);
        return cloneData.filter(father => {
          // console.log(father);
          let branchArr = cloneData.filter(child => father.id == child.parentId);
          branchArr.length > 0 ? (father.children = branchArr) : "";
          return father.parentId == 0; //返回第一层
        });
      }
    },
    methods: {
      closeApplyDialog () {
        this.showApplyDept = false
      },
      // 部门回显-依申请设置
      toggleSelection(rows) {
        this.$nextTick(function () {
          if (rows) {
            rows.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row);
            });
          } else {
            this.$refs.multipleTable.clearSelection();
          }
        })
      },
      // 获取所有部门
      getDeptAll() {
        this.API.deptListNotAllUsingPOST().then(res => {
          this.deptAll = res.data
        })
      },
      // 获取依申请-所有部门
      getSelectedDept() {
        this.API.deptBackUsingPOST().then(res => {
          this.checkedData = res.data
          let result = []
          if (this.deptAll) {
            this.deptAll.map((item) => {
              this.checkedData.map(itemRow => {
                console.log(itemRow.dingId === item.id,itemRow.dingId,item.id)
                if (itemRow.dingId === item.id+'') {
                  result.push(item)
                }
              })
            })
          }
          console.log(result)
          this.toggleSelection(result)
        })
      },
      // 全选
      handleSelectionChange(val) {
        this.selectData = val
      },
      handleSizeChange(val) {
        this.searchDto.pageSize = val;
        this.getDepartment(1);
      },
      handleCurrentChange(val) {
        this.getDepartment(val);
      },
      getSelectTreeValue(value) {
        this.valueId = value;
        this.deptView.parentId = value;
        //console.log(this.valueId);
      },
      getDeptType(val) {
        this.$store.dispatch("viewDictUsingPOSTS", {val: val}).then(ret => {
          this.deptTypeList = ret.data;
        });
      },
      delDept(id) {
        this.$confirm("确认删除部门?", "提示").then(() => {
          //console.log(id);
          this.$store.dispatch("deptDelUsingDELETES", {id: id}).then(ret => {
            this.okmsg(ret.data.value);
            this.getDepartment(1);
          });
        });
      },
      resetForm(formName) {
        let d = this.$refs[formName];
        d.resetFields();
        this.getDepartment(1);
      },
      deptEdit(val) {
        val.dingId = val.id;
        val.parentId = val.parentId;
        console.log(val);
        this.$store.dispatch("deptViewEditS", val);
        this.showDeptView = true;
      },
      showDeptViewTrue() {
        this.showDeptView = true;
        this.$store.commit("INIT_DEPT");
      },
      // 依申请部门设置-弹窗
      setApplyDept() {
        this.$nextTick(function () {
          this.showApplyDept = true
          this.getSelectedDept()
        })
      },
      // 依申请部门设置-保存
      saveApplyDept() {
        if (this.selectData) {
          let data = {systemSettingDto: {organizeId: ''}}
          let tem = []
          this.selectData.map((item) => {
            tem.push(item.id)
          })
          data.systemSettingDto.organizeId = tem.join(',')
          this.API.addApplyDeptUsingPOST(data).then(res => {
            this.showApplyDept = false
          })
        }
      },
      saveDeptView(formName) {
        console.log(JSON.stringify(this.deptView));
        this.$refs[formName].validate(valid => {
          if (valid) {
            let tem = {
              departmentDto: this.deptView
            };
            this.$store.dispatch("deptSaveUsingPOSTS", tem).then(ret => {
              if (ret.status == 200) {
                this.okmsg(ret.data.value);
                this.getDepartment(1);
                this.showDeptView = false;
                this.clickID = 0;
                this.$store.commit("INIT_DEPT");
              }
            });
          } else {
            console.log("验证失败!");
            return false;
          }
        });
      },
      //  获取部门列表
      getDepartment(currentPage) {
        this.derive = {};
        let tem = Object.assign(this.searchDto, {pageNumber: currentPage});
        this.$store.dispatch("deptListPageUsingPOSTS", tem).then(ret => {
          if (ret.data.totalRow >= 1) {
            this.exportTheSwitch = false;
          } else {
            this.exportTheSwitch = true;
          }
        });
        this.derive = tem;
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      okmsg(msg) {
        this.$message({
          message: msg,
          type: "success"
        });
      },
      //部门详情
      getDepartmentUsers() {
        var tem = {
          deptIdDto: {
            deptId: this.clickID
          }
        };
        this.$store.dispatch("deptViewUsingPOSTS", tem).then(ret => {
          this.deptView = true;
          //console.log(ret.data);
        });
      },
      getDeptList() {
        this.$store.dispatch("deptListUsingPOSTS").then(ret => {
        });
      }
    },
    components: {
      PageLayout,
      SelectTree
    }
  };
</script>
<style scoped lang="less">
  .wanner {
    margin-left: -25px;
    width: 200px;
  }

  .labdep > :first-child {
    font-size: 16px;
  }

  .right {
    margin-left: 80px;
  }
</style>
